﻿using Microsoft.VisualBasic;
using Newtonsoft.Json;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace md5Tools
{
    public partial class PhotoMd5Tools : Form
    {
        private MySQLHelper mysqlTools = new MySQLHelper();
        private List<String> filterSuffix = new List<String>();
        // show实体类集合
        private List<PhotoMd5Entity> photoEntityList = new List<PhotoMd5Entity>();
        // 当前显示的图片索引（1开始）
        private int photoIndex = 0;

        public PhotoMd5Tools()
        {
            InitializeComponent();
        }
        private void PhotoMd5Tools_Load(object sender, EventArgs e)
        {
            string pwd = ConfigurationManager.AppSettings["pwd"];
            bool state = true;
            while (true)
            {
                pwd = pwd.Trim();
                if (pwd.Length == 0) break;
                String pwdText = Interaction.InputBox("请输入通行证").Trim();
                Console.WriteLine(pwdText);
                if (String.IsNullOrEmpty(pwdText))
                {
                    state = false;
                    break;
                }
                if (pwd.Equals(pwdText)) break;
            }
            if (!state) this.Close();
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            this.pathMath.SelectedIndex = 0;
            this.photoFilesText.Text = ConfigurationManager.AppSettings["photoMoveToFiles"];
            setFilterSuffixSuffix(true);
            if (!File.Exists(PublicTools.configPath))
            {
                if (!Directory.Exists(Path.GetDirectoryName(PublicTools.configPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(PublicTools.configPath));
                }
                OperIni.WriteIni(PublicTools.configPath, "Image", "paperFile", "无语,low,一般,正常,还行,好,nice,装饰,其他");
            }
        }
        private void getMoveImage_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("该操作会移动文件确定要继续吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return;
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() != DialogResult.OK) return;
            var that = this;
            Task.Run(() =>
            {
                List<PhotoMd5Entity> list = new List<PhotoMd5Entity>();
                string[] files = new string[0];
                string folderPath = String.Empty;
                try
                {
                    folderPath = dialog.SelectedPath;
                    //string[] files = Directory.GetFiles(folderPath, "*.jpg");
                    // 改成过滤所有图片后缀格式
                    files = PublicTools.GetDirectoriesImage(folderPath, string.Join(",", filterSuffix));
                    if (files == null || files.Length < 1)
                    {
                        that.updateRunImg(0);
                        this.showLog("未找到数据", 2);
                        return;
                    }
                    else
                    {
                        that.updateRunImg(files.Length);
                    }
                    if (that.photoFilesText.Text.Trim() == String.Empty)
                    {
                        that.photoFilesText.Text = ConfigurationManager.AppSettings["photoMoveToFiles"];
                        that.photoFilesText.Refresh();
                    }
                }
                catch (Exception ex)
                {
                    that.updateRunImg(0);
                    PublicTools.writeLog($@"获取数据失败（{ex.GetType()}）:{ex.Message}");
                    this.showLog($@"获取数据失败（{ex.GetType()}）:{ex.Message}", 3);
                }
                try
                {
                    // 移动文件的目标文件夹
                    String moveFiles = this.photoFilesText.Text.Trim();
                    // 文件的md5
                    string md5 = String.Empty;
                    // 文件名称、后缀
                    string fileName = String.Empty;
                    string fileNameNoSuffix = String.Empty;
                    string fileSuffix = String.Empty;
                    // 结果集
                    List<String> md5List = new List<String>();
                    int runImg = 1;
                    int runImgTotal = files.Length;
                    if (!this.mysqlRadioBtn.Checked)
                    {
                        foreach (string file in files)
                        {
                            that.updateRunImg(runImgTotal, runImg++);
                            String fileDirectories = String.Empty;
                            if (Boolean.Parse(ConfigurationManager.AppSettings["photoMoveToFilesSaveDirectories"].ToString()))
                            {
                                fileDirectories = Path.GetDirectoryName(file);
                                fileDirectories = fileDirectories.Replace(folderPath, "");
                                if (fileDirectories != null && fileDirectories.IndexOf(@"\") == 0)
                                {
                                    fileDirectories = fileDirectories.Substring(1);
                                }
                            }

                            md5 = PublicTools.CalculateMD5(file);
                            fileName = Path.GetFileName(file);
                            fileNameNoSuffix = Path.GetFileNameWithoutExtension(file);
                            fileSuffix = Path.GetExtension(file);
                            PhotoMd5Entity photo = new PhotoMd5Entity(fileName, file, md5);
                            if ((int)this.mysqlTools.ExecuteScalar("select count(*) form tbl_photoMd5") > 0)
                            {
                                photo = this.mysqlTools.ExecuteQueryEntity<PhotoMd5Entity>($"select * form tbl_photoMd5 where md5 = {md5}",
                                    r => new PhotoMd5Entity(int.Parse(r["Id"].ToString()), r["FileName"].ToString(), r["OldFilePath"].ToString(), r["FilePath"].ToString(), r["Md5"].ToString(), r["PaperFile"].ToString(), int.Parse(r["Count"].ToString()), DateTime.Parse(r["CreateTime"].ToString()), DateTime.Parse(r["UpdateTime"].ToString()), r["Description"].ToString(), int.Parse(r["DeleteState"].ToString())));
                                fileName = Path.GetFileName(photo.FilePath);
                                fileNameNoSuffix = Path.GetFileNameWithoutExtension(file);
                                fileSuffix = Path.GetExtension(file);
                                photo.Count += 1;
                                if (Boolean.Parse(ConfigurationManager.AppSettings["photoMoveToFilesSaveDirectories"].ToString()))
                                {
                                    PublicTools.MoveFile(file, Path.Combine(Path.Combine(moveFiles, fileDirectories), $@"repetitive\{fileNameNoSuffix}"), $@"{fileNameNoSuffix}_{photo.Count}{fileSuffix}");
                                }
                                else
                                {
                                    PublicTools.MoveFile(file, $@"{moveFiles}\repetitive\{fileNameNoSuffix}", $@"{fileNameNoSuffix}_{photo.Count}{fileSuffix}");
                                }
                                this.mysqlTools.Update("tbl_photoMd5", PublicTools.ConvertEntityToDictionary(photo), $" Id = {photo.Id} ");
                            }
                            else
                            {
                                if (Boolean.Parse(ConfigurationManager.AppSettings["photoMoveToFilesSaveDirectories"].ToString()))
                                {
                                    photo.FilePath = PublicTools.MoveFile(file, Path.Combine(moveFiles, fileDirectories));
                                }
                                else
                                {
                                    photo.FilePath = PublicTools.MoveFile(file, moveFiles);
                                }
                                // 移动后修改实体类文件的路径，并保存
                                if (mysqlTools.Insert("tbl_photoMd5", PublicTools.ConvertEntityToDictionary(photo, new string[] { "Id" })) > 0)
                                {
                                    PublicTools.writeLog($"{photo.FileName}保存成功", 2, "mysqlLog_");
                                }
                            }
                            list.Add(photo);
                        }
                    }
                    else
                    {
                        int index = 1;
                        foreach (string file in files)
                        {
                            that.updateRunImg(runImgTotal, runImg++);
                            String fileDirectories = String.Empty;
                            if (Boolean.Parse(ConfigurationManager.AppSettings["photoMoveToFilesSaveDirectories"].ToString()))
                            {
                                fileDirectories = Path.GetDirectoryName(file);
                                fileDirectories = fileDirectories.Replace(folderPath, "");
                                if (fileDirectories != null && fileDirectories.IndexOf(@"\") == 0)
                                {
                                    fileDirectories = fileDirectories.Substring(1);
                                }
                            }
                            md5 = PublicTools.CalculateMD5(file);
                            fileName = Path.GetFileName(file);
                            fileNameNoSuffix = Path.GetFileNameWithoutExtension(file);
                            fileSuffix = Path.GetExtension(file);
                            PhotoMd5Entity photo = new PhotoMd5Entity(fileName, file, md5);
                            if (!md5List.Contains(md5))
                            {
                                Console.WriteLine("没重复");
                                photo.Id = index++;
                                if (Boolean.Parse(ConfigurationManager.AppSettings["photoMoveToFilesSaveDirectories"].ToString()))
                                {
                                    photo.FilePath = PublicTools.MoveFile(file, Path.Combine(moveFiles, fileDirectories));
                                }
                                else
                                {
                                    photo.FilePath = PublicTools.MoveFile(file, moveFiles);
                                }
                                list.Add(photo);
                                md5List.Add(md5);
                            }
                            else
                            {
                                Console.WriteLine("重复");
                                photo = list[md5List.IndexOf(md5)];
                                photo.Count += 1;
                                fileName = Path.GetFileName(photo.FileName);
                                fileNameNoSuffix = Path.GetFileNameWithoutExtension(photo.FileName);
                                fileSuffix = Path.GetExtension(photo.FileName);
                                fileDirectories = Path.GetDirectoryName(photo.FilePath);

                                if (Boolean.Parse(ConfigurationManager.AppSettings["photoMoveToFilesSaveDirectories"].ToString()))
                                {
                                    try
                                    {
                                        // 重复保存文件夹的情况下，直接移动到重复文件的文件夹中
                                        PublicTools.MoveFile(file, Path.Combine(fileDirectories, $@"repetitive\{fileNameNoSuffix}"), $@"{fileNameNoSuffix}_{photo.Count}{fileSuffix}");
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                }
                                else
                                {
                                    PublicTools.MoveFile(file, Path.Combine(moveFiles, $@"repetitive\{fileNameNoSuffix}"), $@"{fileNameNoSuffix}_{photo.Count}{fileSuffix}");
                                }
                            }
                        }
                        EPPlusTools ePPlusTools = new EPPlusTools();
                        String path = ePPlusTools.createTemplate();
                        Console.WriteLine(JsonConvert.SerializeObject(PublicTools.ConvertListToDataTable<PhotoMd5Entity>(list)));
                        ePPlusTools.WriteDataTable(PublicTools.ConvertListToDataTable<PhotoMd5Entity>(list), null, null);
                        ePPlusTools.saveExecel(path);
                        ePPlusTools.openFile(path);
                    }
                    this.showLog($"记录并移动完成。", 1);
                }
                catch (Exception ex)
                {
                    PublicTools.writeLog($"({ex.GetType()}):记录移动出错，{ex.Message}", 3);
                    EPPlusTools ePPlusTools = new EPPlusTools();
                    String path = ePPlusTools.createTemplate(null, null, true);
                    Console.WriteLine(JsonConvert.SerializeObject(PublicTools.ConvertListToDataTable<PhotoMd5Entity>(list)));
                    ePPlusTools.WriteDataTable(PublicTools.ConvertListToDataTable<PhotoMd5Entity>(list), null, null);
                    ePPlusTools.saveExecel(path);
                    ePPlusTools.openFile(path);
                    this.showLog($"记录移动出错，{ex.Message}", 3);
                }
            });
        }
        /// <summary>
        /// 更新加载进度的
        /// </summary>
        /// <param name="total">总数</param>
        /// <param name="index">当前数</param>
        private void updateRunImg(int total, int index = 0)
        {
            if (this.runImgTotal.InvokeRequired)
            {
                this.runImgTotal.Invoke(new Action(() =>
                {
                    string totalText = this.runImgTotal.Text;
                    if (!totalText.Trim().Equals(total.ToString()))
                    {
                        this.runImgTotal.Text = total.ToString();
                        this.runImgTotal.Refresh();
                    }

                }));
            }
            else
            {
                string totalText = this.runImgTotal.Text;
                if (!totalText.Trim().Equals(total.ToString()))
                {
                    this.runImgTotal.Text = total.ToString();
                    this.runImgTotal.Refresh();
                }
            }
            if (this.runImg.InvokeRequired)
            {
                this.runImg.Invoke(new Action(() =>
                {
                    this.runImg.Text = index.ToString();
                    this.runImg.Refresh();
                }));
            }
            else
            {
                this.runImg.Text = index.ToString();
                this.runImg.Refresh();
            }
            if (this.runLoading.InvokeRequired)
            {
                this.runLoading.Invoke(new Action(() =>
                {
                    this.runLoading.Text = (total == 0 ? 0 : (int)(index / (float)total * 100)) + "%";
                    this.runLoading.Location = new Point(25 + (total == 0 ? 0 : (int)(index / (float)total * 150)), 140);
                    this.runLoading.Refresh();
                }));
            }
            else
            {
                this.runLoading.Text = (total == 0 ? 0 : (int)(index / (float)total * 100)) + "%";
                this.runLoading.Location = new Point(25 + (total == 0 ? 0 : (int)(index / (float)total * 150)), 140);
                this.runLoading.Refresh();
            }
            if (this.progressBar1.InvokeRequired)
            {
                this.progressBar1.Invoke(new Action(() =>
                {
                    this.progressBar1.Value = (total == 0 ? 0 : (int)(index / (float)total * 100));
                }));
            }
            else
            {
                this.progressBar1.Value = (total == 0 ? 0 : (int)(index / (float)total * 100));
            }
        }
        /// <summary>
        /// 显示log
        /// </summary>
        /// <param name="log"></param>
        private void showLog(String log, int grade = 0)
        {
            Color color = TextBox.DefaultForeColor;
            switch (grade)
            {
                case 1:
                    color = Color.Yellow;
                    break;
                case 2:
                    color = Color.LightSkyBlue;
                    break;
                case 3:
                    color = Color.FromArgb(255, 128, 128);
                    break;
                default:
                    color = TextBox.DefaultBackColor;
                    break;
            }
            if (this.showLogText.InvokeRequired)
            {
                this.showLogText.Invoke(new Action(() =>
                {
                    this.showLogText.Text = DateTime.Now + ":\r\n" + log;
                    this.showLogText.BackColor = color;
                }));
            }
            else
            {
                this.showLogText.Text = DateTime.Now + ":\r\n" + log;
                this.showLogText.BackColor = color;
            }
        }

        private void writePhotoPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() != DialogResult.OK) return;
            Task.Run(() =>
            {
                string folderPath = dialog.SelectedPath;
                //string[] files = Directory.GetFiles(folderPath, "*.jpg");
                // 改成过滤所有图片后缀格式
                string[] files = PublicTools.GetDirectoriesImage(folderPath, string.Join(",", filterSuffix));
                this.updateRunImg(files.Length);
                if (files == null || files.Length < 1)
                {
                    this.showLog("未找到数据", 2);
                    return;
                }
                DataTable data = new DataTable();
                // 检查列是否存在于数据表中，如果不存在，先添加列
                data.Columns.Add("Id");
                data.Columns.Add("FileName");
                data.Columns.Add("FilePath");
                data.Columns.Add("Md5");

                int idIndex = 0;

                foreach (string file in files)
                {
                    this.updateRunImg(files.Length, idIndex);

                    // 创建一个新的DataRow实例
                    DataRow row = data.NewRow();

                    // 设置row的各个字段值
                    row["Id"] = ++idIndex;
                    row["FileName"] = Path.GetFileName(file);
                    row["FilePath"] = file;
                    row["Md5"] = PublicTools.CalculateMD5(file);
                    // 将这个row添加到DataTable中
                    data.Rows.Add(row);
                }
                Console.WriteLine(data.Rows.Count);
                EPPlusTools ePPlusTools = new EPPlusTools();
                String path = ePPlusTools.createTemplate();
                ePPlusTools.WriteDataTable(data, null, null);
                ePPlusTools.saveExecel(path);
                this.updateRunImg(files.Length, idIndex);
                ePPlusTools.openFile(path);
            });
        }

        private void pathBtnRefresh_Click(object sender, EventArgs e)
        {
            fileNameBox.Controls.Clear();
            //String paperFile = ConfigurationManager.AppSettings["paperFile"];
            String paperFile;
            OperIni.ReadIni(PublicTools.configPath, "Image", "paperFile", out paperFile);
            Console.WriteLine(paperFile);
            string[] strArray = paperFile.Split(new char[] { ',' });
            foreach (String str in strArray)
            {
                Button btn = new Button();
                btn.Text = str;
                // 给按钮添加一个点击方法
                btn.Click += new EventHandler(Button_Click);

                // 定义点击方法
                void Button_Click(object sender2, EventArgs e2)
                {
                    // 在这里添加点击按钮后要执行的代码
                    this.pathToComboBox.Text = Path.Combine(ConfigurationManager.AppSettings["paperFilePath"], ((Button)sender2).Text);
                }
                fileNameBox.Controls.Add(btn);
            }
            this.pathToComboBox.Text = ConfigurationManager.AppSettings["paperFilePath"];
        }
        // 导入
        private void importBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.excelRadioBtn.Checked)
                {
                    // 导入Excel
                    String path = String.Empty;

                    try
                    {
                        Thread t = new Thread((ThreadStart)(() =>
                        {
                            // 将出现这个异常的语句放到这里面
                            OpenFileDialog openFileDialog = new OpenFileDialog();
                            openFileDialog.InitialDirectory = Path.Combine(PublicTools.appPath , "data");//注意这里写路径时要用c:\\而不是c:\
                            openFileDialog.Filter = "excel文件|*.xlsx|所有文件|*.*";
                            openFileDialog.RestoreDirectory = true;
                            openFileDialog.FilterIndex = 1;
                            if (openFileDialog.ShowDialog() == DialogResult.OK)
                            {
                                path = openFileDialog.FileName;
                            }
                        }
                        ));
                        t.SetApartmentState(ApartmentState.STA);
                        t.Start();
                        t.Join();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"文件选择异常，{ex.Message}");
                    }
                    // 文件路径为空时不继续执行
                    if (String.IsNullOrEmpty(path)) return;

                    using (ExcelPackage package = new ExcelPackage(new FileInfo(path)))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                        // 获取Excel中的行数和列数
                        int rowCount = worksheet.Dimension.Rows;
                        this.updateRunImg(rowCount);
                        int columnCount = worksheet.Dimension.Columns;
                        // 用于将单行数据组合成一个对象
                        PhotoMd5Entity photoMd5 = null;
                        // 表头
                        List<String> key = new List<String>();
                        List<PhotoMd5Entity> photoMds = new List<PhotoMd5Entity>();
                        for (int col = 1; col <= columnCount; col++)
                        {
                            // 通过索引获取单元格值
                            key.Add((String)worksheet.Cells[1, col].Value);
                        }


                        // 遍历每一行
                        for (int row = 2; row <= rowCount; row++)
                        {
                            this.updateRunImg(rowCount, row);

                            List<Object> value = new List<Object>();
                            // 遍历每一列
                            for (int col = 1; col <= columnCount; col++)
                            {
                                // 通过索引获取单元格值
                                value.Add(worksheet.Cells[row, col].Value);
                            }
                            photoMd5 = new PhotoMd5Entity();
                            PublicTools.setTypeValue<PhotoMd5Entity>(ref photoMd5, key, value);
                            Console.WriteLine(JsonConvert.SerializeObject(photoMd5));
                            photoMds.Add(photoMd5);
                        }
                        photoEntityList = photoMds;
                    }
                }
                else
                {
                    // 导入数据库
                    MySQLHelper mysql = new MySQLHelper();
                    photoEntityList = mysql.ExecuteQuery<PhotoMd5Entity>("select * form tbl_photoMd5", r => new PhotoMd5Entity(int.Parse(r["Id"].ToString()), r["FileName"].ToString(), r["OldFilePath"].ToString(), r["FilePath"].ToString(), r["Md5"].ToString(), r["PaperFile"].ToString(), int.Parse(r["Count"].ToString()), DateTime.Parse(r["CreateTime"].ToString()), DateTime.Parse(r["UpdateTime"].ToString()), r["Description"].ToString(), int.Parse(r["DeleteState"].ToString())));
                }
            }
            catch (Exception ex)
            {
                PublicTools.writeLog($"importBtn_Click({ex.GetType()}):导入数据出错，{ex.Message}", 3);
                this.showLog($"importBtn_Click({ex.GetType()}):导入数据出错，{ex.Message}", 3);
            }
            this.showPhoto.Image = null;
            this.totalGroupBox.Text = $"Total：0";
            this.fileNameText.Text = String.Empty;
            this.filePathText.Text = String.Empty;
            if (photoEntityList != null && photoEntityList.Count > 0)
            {
                this.photoIndex = 1;
                this.totalGroupBox.Text = $"Total：{photoEntityList.Count}";
                refreshShowImage();
            }
        }

        private void upBtn_Click(object sender, EventArgs e)
        {
            if (photoIndex <= 1 || photoEntityList == null || photoEntityList.Count < 1)
            {
                photoIndex = (photoEntityList != null ? 1 : 0);
                this.showLog("没有上一张了！！！", 2);
                return;
            }
            photoIndex--;
            refreshShowImage();
        }

        private void nextBtn_Click(object sender, EventArgs e)
        {
            if (photoEntityList == null || photoEntityList.Count < 1 || photoIndex >= photoEntityList.Count)
            {
                try
                {
                    photoIndex = photoEntityList.Count;
                }
                catch (Exception ex)
                {
                    photoIndex = 0;
                }
                this.showLog("没有下一张了！！！", 2);
                return;
            }
            photoIndex++;
            refreshShowImage();
        }

        private void jumpToText_KeyDown(object sender, KeyEventArgs e)
        {
            // 如果按下的是回车键
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    // 在这里添加按下回车键后要执行的代码
                    int index = Convert.ToInt32(this.jumpToText.Text);
                    if (index > 0 && photoEntityList != null && index <= photoEntityList.Count)
                    {
                        photoIndex = index;
                        refreshShowImage();
                    }
                    else
                    {
                        this.jumpToText.Text = photoIndex.ToString();
                    }
                }
                catch (Exception ex)
                {
                    PublicTools.writeLog("输入的跳转索引存在问题", 3);
                    this.jumpToText.Text = photoIndex.ToString();
                }
            }
            else
            {
                // 如果输入的不是数字和控制键，则取消输入
                if (!Char.IsNumber((char)e.KeyValue) && !Char.IsControl((char)e.KeyValue))
                {
                    e.Handled = true;
                }
            }
        }

        private void refreshShowImage()
        {
            try
            {
                //this.showPhoto.Image = Image.FromFile(photoPathList[photoIndex - 1]);
                this.jumpToText.Text = photoIndex.ToString();
                string filePath = photoEntityList[photoIndex - 1].FilePath ?? "";
                using (var img = Image.FromFile(filePath))
                {
                    this.showPhoto.Image = new Bitmap(img);
                }
                string fileName = Path.GetFileName(filePath);
                this.toolTip1.SetToolTip(this.showPhoto, fileName);
                this.fileNameText.Text = fileName;
                this.filePathText.Text = filePath;
                this.showPaperFileText.Text = photoEntityList[photoIndex - 1].PaperFile;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"({ex.GetType()}):未找到文件，{ex.Message}");
            }
        }

        private void moveBtn_Click(object sender, EventArgs e)
        {
            try
            {
                String moveToPath = this.pathToComboBox.Text.Trim();
                string type = String.Empty;
                PhotoMd5Entity entity = photoEntityList[photoIndex - 1];
                entity.OldFilePath = entity.FilePath;
                entity.FilePath = PublicTools.MoveFile(entity.FilePath, moveToPath);
                entity.PaperFile = Path.GetDirectoryName(entity.FilePath).Substring(Path.GetDirectoryName(entity.FilePath).LastIndexOf(@"\") + 1);
                this.showLog($"原：{Path.GetFileName(entity.OldFilePath)}移动完成-新：{Path.GetFileName(entity.FilePath)}", 1);
            }
            catch (Exception ex)
            {
                this.showLog($"移动失败！{ex.Message}", 3);
            }
        }

        private void copyBtn_Click(object sender, EventArgs e)
        {
            try
            {
                String moveToPath = this.pathToComboBox.Text.Trim();
                PhotoMd5Entity entity = photoEntityList[photoIndex - 1];
                entity.OldFilePath = entity.FilePath;
                entity.FilePath = PublicTools.CopyFile(entity.FilePath, moveToPath);
                if (String.IsNullOrEmpty(entity.PaperFile))
                {
                    entity.PaperFile = Path.GetDirectoryName(entity.FilePath).Substring(Path.GetDirectoryName(entity.FilePath).LastIndexOf(@"\") + 1);
                }
                this.showLog($"原：{Path.GetFileName(entity.OldFilePath)},新：{Path.GetFileName(entity.FilePath)}复制完成", 1);
            }
            catch (Exception ex)
            {
                this.showLog($"复制失败！{ex.Message}", 3);
            }
        }

        private void outBtn_Click(object sender, EventArgs e)
        {
            DataTable data = PublicTools.ConvertListToDataTable(photoEntityList);
            EPPlusTools ePPlusTools = new EPPlusTools();
            String path = ePPlusTools.createTemplate();
            ePPlusTools.WriteDataTable(data, null, null);
            ePPlusTools.saveExecel(path);
            ePPlusTools.openFile(path);
        }

        private void testBtn_Click(object sender, EventArgs e)
        {
            this.filterSuffixCheck.Visible = !this.filterSuffixCheck.Visible;
            if (!this.filterSuffixCheck.Visible)
            {
                this.setFilterSuffixSuffix();
            }
        }

        private void setFilterSuffixSuffix(bool reset = false)
        {
            if (reset)
            {
                for (int i = 0; i < this.filterSuffixCheck.Items.Count; i++)
                {
                    filterSuffixCheck.SetItemChecked(i, true);
                }
            }
            this.filterSuffix.Clear();
            for (int i = 0; i < this.filterSuffixCheck.Items.Count; i++)
            {
                if (filterSuffixCheck.GetItemChecked(i))
                {
                    String value = filterSuffixCheck.GetItemText(filterSuffixCheck.Items[i]);
                    filterSuffix.Add(value);
                }
            }
        }

        private void PhotoMd5Tools_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 提示是否要将未获取导出的数据导出
            if (photoEntityList != null && photoEntityList.Count > 0)
            {
                DataTable data = PublicTools.ConvertListToDataTable(photoEntityList);
                EPPlusTools ePPlusTools = new EPPlusTools();
                String path = ePPlusTools.createTemplate(null, null, true);
                ePPlusTools.WriteDataTable(data, null, null);
                ePPlusTools.saveExecel(path);
            }
        }

        private void delecteDirectory_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var that = this;
                Task.Run(() =>
                {
                    try
                    {
                        int count = PublicTools.deleteEmptyDirectories(dialog.SelectedPath);
                        this.showLog($@"删除文件夹成功,删除{count}个文件夹", 2);
                    }
                    catch (Exception ex)
                    {
                        PublicTools.writeLog($@"刪除文件夹失败（{ex.GetType()}）:{ex.Message}");
                        this.showLog($@"刪除文件夹失败（{ex.GetType()}）:{ex.Message}", 3);
                    }
                });
            }
        }

        private void openImagePath_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", "/select," + this.filePathText.Text);
        }

        private void copyImagePath_Click(object sender, EventArgs e)
        {
            //两个都可以将内容复制到剪切板
            //Clipboard.SetDataObject(this.filePathText.Text,true);
            this.filePathText.Copy();
            this.showLog("拷贝成功！", 2);
        }

        private void pathBtnAdd_Click(object sender, EventArgs e)
        {
            string one = this.pathTextName.Text.Trim();
            string two = this.pathTextNameNew.Text.Trim();
            String paperFile;
            OperIni.ReadIni(PublicTools.configPath, "Image", "paperFile", out paperFile);
            int paperFIleLength = paperFile.Length;
            string[] paperFileArray = paperFile.Split(new char[] { ',' });
            HashSet<string> set = paperFileArray.ToHashSet();
            switch (this.pathBtnAdd.Text)
            {
                case "add":
                    set.Add(two);
                    break;
                case "update":
                    if (set.Contains(one))
                    {
                        set.Remove(one);
                    }
                    if (!paperFileArray.Contains(two))
                    {
                        set.Add(two);
                    }
                    break;
                case "delete":
                    if (set.Contains(two))
                    {
                        set.Remove(two);
                    }
                    break;
            }
            paperFile = String.Join(",", set);

            OperIni.WriteIni(PublicTools.configPath, "Image", "paperFile", paperFile);
            this.pathBtnRefresh_Click(sender, e);
        }

        private void pathAddRadio_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void pathMath_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.pathBtnAdd.Text = this.pathMath.GetItemText(this.pathMath.SelectedItem);
            if (this.pathBtnAdd.Text == "add" || this.pathBtnAdd.Text == "delete")
            {
                this.pathTextName.Text = "";
                this.pathTextName.Enabled = false;
            }
            else
            {
                this.pathTextName.Enabled = true;
            }
;
        }

        private void showPhotoBtn_Click(object sender, EventArgs e)
        {
            if ("-".Equals(this.showPhotoBtn.Text))
            {
                this.showPhotoBtn.Text = "+";
                this.pictureBox1.Visible = false;
            }
            else
            {
                this.showPhotoBtn.Text = "-";
                this.pictureBox1.Visible = true;
            }
        }
    }
}
